layui.define(['jquery', 'element', 'quesElement', 'form', 'quesLogic'], function (exports) {
	var MOD_NAME = 'ques',
		$ = layui.jquery,
		element = layui.element,
		form = layui.form;
		quesElement = layui.quesElement,
		sortable = layui.sortable,
		quesLogic = layui.quesLogic;

	var ques = function (opt) {
		this.option = opt;
		this.dataList = [];		//存储题目
		// this.id_index = {};		//题目id-题号映射
		this.cur_id = ''; 	//当前选中id
		this.cur_no = 0;	//当前选中题号
		this.cnt_id = 0;	//最大id
		this.cnt_no = 0;	//最大题号
		this.id_block = {};
	};


	function generateRandomId() {
		return Date.now().toString(36) + Math.random().toString(36).substring(2, 5);
	};

	function getIndexOfElement(e) {
		return Array.prototype.indexOf.call(e.parentNode.children, e);
	};

	//重新编号
	ques.prototype.reIndex = function (id, op, new_i, old_i) {
		var that = this;
		Array.from(document.getElementsByClassName('ques-index')).forEach(function (item, index) {
			item.innerHTML = String(index + 1) + ".";
			// that.id_index[item.getAttribute("name")] = index + 1;
		});
		Array.from(document.getElementsByClassName('list-index')).forEach(function (item, index) {
			item.innerHTML = String(index + 1) + ". ";
		});
		if(op === 'sort') {
			if(new_i > old_i) {
				var tmp = that.dataList[old_i];
				for (let i = old_i; i < new_i; i++) {
					that.dataList[i] = that.dataList[i+1];
				}
				that.dataList[new_i] = tmp;
			}
			else if(new_i < old_i) {
				var tmp = that.dataList[old_i];
				for (let i = old_i; i > new_i; i--) {
					that.dataList[i] = that.dataList[i-1];
				}
				that.dataList[new_i] = tmp;
			}
		}
		for (let i = 0; i < that.dataList.length; i++) {
			// that.dataList[i].index = that.id_index[that.dataList[i].id];
			that.dataList[i].index = i+1;
		}
		if (id !== undefined) {
			that.cur_id = id;
			$(`div[data-id="${id}"]`).click();
		}
	};

	ques.prototype.render = function (opt) {
		var that = this,
			options = opt;
		quesLogic.init(that.dataList);

		//生成左侧基础组件
		var left_tab1_html = "";
		$.each(quesElement.c0.list, function (index, cat) {
			var name = quesElement[cat]['name'];
			left_tab1_html += `<li class="layui-menu-item-group layui-menu-item-down">
								<div class="layui-menu-body-title"><i class="layui-icon layui-icon-down"></i>${name}</div>
								<ul class="menu menu1">`;
			quesElement[cat]['list'].forEach(item => {
				left_tab1_html += `<li><div class="layui-menu-body-item m1 ${item.split('.')[0]}">${item.split('.')[1]}</div></li>`;
			});
			left_tab1_html += `</ul></li>`;
		});
		$(options.elem).append(left_tab1_html);

		//生成左侧题库
		var left_tab2_html = "";
		$.ajax({
			type: "GET",
			url: "http://127.0.0.1:8000/getQues/",
			dataType: "json",
			async: false,
			success: function(data) {
				$.each(data.list, function(index, elem) {
					left_tab2_html += `<li class="layui-menu-item-group layui-menu-item-down">
								<div style="float:right;"><a role="button" class="getall" title="查看全部"><i class="layui-icon layui-icon-search"></i></a></div>
								<div class="layui-menu-body-title"><i class="layui-icon layui-icon-down"></i>${elem.type}
								</div>
								<ul class="menu menu2">`;
					elem.items.forEach(item => {
						left_tab2_html += `<li><div class="layui-menu-body-item m2 ${item.id}">${item.title}</div></li>`;
						that.id_block[item.id] = item;
					});
					left_tab2_html += `</ul></li>`;
				});
				$('#left-tab2').append(left_tab2_html);
			}
		});
	

		//组件渲染器
		var quesRender = {
			//中间问卷渲染
			midContentRender: function (obj) {
				var res = `
					<div class="layui-form-item item act selected" style="margin-top: 40px;" data-id="${obj.id}">
						<div class="layui-form-item">
                        <label name="${obj.id}" class="layui-form-label ques-index handle act required" >${obj.index}.</label>
                        <input name="${obj.id}" class="layui-input title act" type="text" placeholder="请输入题目" style="width: 400px;" value="${obj.title}">
						</div>`;

				res += this[obj.type].renderContent(obj);

				res += `
						<div class="layui-form-item">
                        <div class="layui-btn-container">
						${obj.type === 'radio' || obj.type === 'checkbox' ?
							`<button type="button" class="layui-btn layui-btn-sm add-other act" data-id="${obj.id}" style="float: left;">添加其他项</button>` : ''
						}
						${obj.type === 'radio' || obj.type === 'checkbox' || obj.type === 'select' ?
							`<button type="button" class="layui-btn layui-btn-sm import-opt act" data-id="${obj.id}" style="float: left;">批量导入选项</button>` : ''
						}
                            <button type="button" class="layui-btn layui-btn-sm copy-item act" data-id="${obj.id}" style="float: right;">复制</button>
                            <button type="button" class="layui-btn layui-btn-sm delete-item act" data-id="${obj.id}" style="float: right;">删除</button>
                        </div>
						</div>
                    </div>`;

				return res;
			},
			//右侧设置页渲染
			propertyRender: function (obj) {
				var res = `
							<div class="layui-form-item" >
                                <label class="layui-form-label">题号</label>
                                <div class="layui-input-block">
                                <input type="text" name="id" class="layui-input" value="${obj.index}" readonly>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">标识</label>
                                <div class="layui-input-block">
                                <input type="text" name="id" class="layui-input" value="${obj.id}" readonly>
                                </div>
                            </div>
                            <div class="layui-form-item" >
                                <label class="layui-form-label">标题</label>
                                <div class="layui-input-block">
                                <input type="text" name="title" class="layui-input" placeholder="请输入" value="${obj.title}">
                                </div>
                            </div>
                            <div class="layui-form-item" >
                                <label class="layui-form-label">类型</label>
                                <div class="layui-input-block">
                                <input type="text" name="id" class="layui-input" value="${obj.type}" readonly>
                                </div>
                            </div>
                            <div class="layui-form-item">
								<label class="layui-form-label">必填</label>
								<div class="layui-input-block">
								<input type="checkbox" name="open" lay-skin="switch" lay-filter="reqSwitch" title="是|否" ${obj.config.required ? 'checked' : ''}>
								</div>
							</div>`;
				return res + this[obj.type].renderProperty(obj);
			},
			//预览页渲染
			previewRender: function(obj) {
				var res = `
					<div class="layui-form-item ques" style="margin-top: 40px;display: block;" data-id="${obj.id}">
						<div class="layui-form-item">
							<label name="${obj.id}" class="prev-index layui-form-label ${obj.config.required ? 'required' : ''}" >${obj.index}.</label>
							<div class="layui-input-inline" style="width: 480px;margin-top:10px;font-weight: bold;">
								${obj.title}
							</div>
						</div>`;

				res += this[obj.type].renderPreview(obj);

				res += `</div>`;

				return res;
			},
			radio: {
				renderContent: function (obj) {
					var res = `<div class="xxx ${obj.id} act">`;
					//循环添加选项
					for (let i = 0; i < obj.config.options.length; i++) {
						res += this.renderOption(obj,i);
					}
					res += `</div>`;
					return res;
				},
				renderProperty: function () {
					var res = `
                            <div class="layui-form-item" >
                                <label class="layui-form-label">专属属性</label>
                                <div class="layui-input-block">
                                <input type="text" name="id" class="layui-input" value="radio" readonly>
                                </div>
                            </div>`;
					return res;
				},
				renderPreview: function(obj) {
					var res = `<div >`;
					//循环添加选项
					for (let i = 0; i < obj.config.options.length; i++) {
						if(obj.config.options[i].other) {
							res += `
							<div class="layui-form-item">
								<label class="layui-form-label" ></label>
								<div class="layui-input-inline" >
									<input class="other-opt act" lay-filter="other-opt" name="${obj.id}" value="${obj.config.options[i].value}"
									title="${obj.config.options[i].text}" type="radio" lay-verify="${obj.config.required ? 'otherReq' : ''}">
									<input data-id="${obj.id}" class="layui-input other-input act" placeholder="用户填其他项" type="text" style="display:none;margin-left:30px;">
								</div>
							</div>
							`;
						}
						else{
							res += `
							<div class="layui-form-item">
								<label class="layui-form-label" ></label>
								<div class="layui-input-inline" >
									<input lay-filter="common-opt" name="${obj.id}" value="${obj.config.options[i].value}"
									title="${obj.config.options[i].text}" type="radio" lay-verify="${obj.config.required ? 'otherReq' : ''}">
								</div>
							</div>
							`;
						}
					}
					res += `</div>`;
					return res;
				},
				renderOption: function(obj,i) {
					var res;
					if(obj.config.options[i].other) {
						res = `
						<div class="layui-form-item opt-div act">
							<label class="layui-form-label handle" ><i class="layui-icon layui-icon-more-vertical drag-icon" style="display:none"></i></label>
							<div class="layui-input-inline" style="width: 20px;">
								<input type="radio" disabled>
							</div>
							<div class="layui-input-inline" style="width: 290px;">
								<input name="${obj.id}@${generateRandomId()}" value="${obj.config.options[i].text}" class="layui-input opt act" type="text" >
								<input placeholder="用户填其他项" class="layui-input" type="text" readonly>
							</div>
							<div class="layui-input-inline inline-opt" style="width: 80px;height:38px;display:none;">
								<i class="layui-icon layui-icon-add-circle add-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 4px;float:left"></i>
								<i class="layui-icon layui-icon-reduce-circle del-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 0px;float:left;"></i>
							</div>
						</div>
						`;
					}
					else {
						res = `
							<div class="layui-form-item opt-div act">
								<label class="layui-form-label handle" ><i class="layui-icon layui-icon-more-vertical drag-icon" style="display:none"></i></label>
								<div class="layui-input-inline" style="width: 20px;">
									<input type="radio" disabled>
								</div>
								<div class="layui-input-inline" style="width: 290px;">
									<input name="${obj.id}@${generateRandomId()}" value="${obj.config.options[i].text}" class="layui-input opt act" type="text" >
								</div>
								<div class="layui-input-inline inline-opt" style="width: 80px;height:38px;display:none;">
									<i class="layui-icon layui-icon-add-circle add-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 4px;float:left"></i>
									<i class="layui-icon layui-icon-reduce-circle del-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 0px;float:left;"></i>
								</div>
							</div>
							`;
					}
					return res;
				}
			},
			checkbox: {
				renderContent: function (obj) {
					var res = `<div class="xxx ${obj.id}">`;
					//循环添加选项
					for (let i = 0; i < obj.config.options.length; i++) {
						res += this.renderOption(obj,i);
					}
					res += `</div>`;
					return res;
				},
				renderProperty: function () {
					var res = `
						<div class="layui-form-item" >
							<label class="layui-form-label">专属属性</label>
							<div class="layui-input-block">
							<input type="text" name="id" class="layui-input" value="checkbox" readonly>
							</div>
						</div>`;
					return res;
				},
				renderPreview: function(obj) {
					var res = `<div >`;
					//循环添加选项
					for (let i = 0; i < obj.config.options.length; i++) {
						if(obj.config.options[i].other) {
							res += `
							<div class="layui-form-item">
								<label class="layui-form-label" ></label>
								<div class="layui-input-inline" >
									<input class="other-opt act" lay-filter="other-opt" name="${obj.id}" value="${obj.config.options[i].value}" 
									title="${obj.config.options[i].text}" type="checkbox" lay-verify="${obj.config.required ? 'otherReq' : ''}">
									<input data-id="${obj.id}" class="layui-input other-input act" placeholder="用户填其他项" type="text" style="display:none;margin-left:30px;">
								</div>
							</div>
							`;
						}
						else {
							res += `
							<div class="layui-form-item">
								<label class="layui-form-label" ></label>
								<div class="layui-input-inline" >
									<input lay-filter="prev-trig" type="checkbox" name="${obj.id}" value="${obj.config.options[i].value}" title="${obj.config.options[i].text}" lay-verify="${obj.config.required ? 'otherReq' : ''}">
								</div>
							</div>
							`;
						}
					}
					res += `</div>`;
					return res;
				},
				renderOption: function(obj,i) {
					var res;
					if(obj.config.options[i].other) {
						res = `
						<div class="layui-form-item opt-div act">
							<label class="layui-form-label handle" ><i class="layui-icon layui-icon-more-vertical drag-icon" style="display:none"></i></label>
							<div class="layui-input-inline" style="width: 20px;">
								<input name="${obj.id}" value="${obj.config.options[i].value}" type="checkbox" disabled>
							</div>
							<div class="layui-input-inline" style="width: 290px;">
								<input name="${obj.id}@${generateRandomId()}" value="${obj.config.options[i].text}" class="layui-input opt act" type="text" >
								<input placeholder="用户填其他项" class="layui-input" type="text" readonly>
							</div>
							<div class="layui-input-inline inline-opt" style="width: 80px;height:38px;display:none;">
								<i class="layui-icon layui-icon-add-circle add-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 4px;float:left"></i>
								<i class="layui-icon layui-icon-reduce-circle del-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 0px;float:left;"></i>
							</div>
						</div>
						`;
					}
					else {
						res = `
						<div class="layui-form-item opt-div act">
							<label class="layui-form-label handle" ><i class="layui-icon layui-icon-more-vertical drag-icon" style="display:none"></i></label>
							<div class="layui-input-inline" style="width: 20px;">
								<input name="${obj.id}" value="${obj.config.options[i].value}" type="checkbox" disabled>
							</div>
							<div class="layui-input-inline" style="width: 290px;">
								<input name="${obj.id}@${generateRandomId()}" value="${obj.config.options[i].text}" class="layui-input opt act" type="text" >
							</div>
							<div class="layui-input-inline inline-opt" style="width: 80px;height:38px;display:none;">
								<i class="layui-icon layui-icon-add-circle add-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 4px;float:left"></i>
								<i class="layui-icon layui-icon-reduce-circle del-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 0px;float:left;"></i>
							</div>
						</div>
						`;
					}
					return res;
				}
			},
			select: {
				renderContent: function (obj) {
					var res = `<div class="xxx ${obj.id}">`;
					//循环添加选项
					for (let i = 0; i < obj.config.options.length; i++) {
						res += this.renderOption(obj,i);
					}
					res += `</div>`;
					return res;
				},
				renderProperty: function () {
					var res = `
						<div class="layui-form-item" >
							<label class="layui-form-label">专属属性</label>
							<div class="layui-input-block">
							<input type="text" name="id" class="layui-input" value="checkbox" readonly>
							</div>
						</div>`;
					return res;
				},
				renderPreview: function(obj) {
					var res = `<div >`;
					res += `<div class="layui-form-item"><label class="layui-form-label"></label><div class="layui-inline" style="width:290px;">`;
					res += `<select lay-filter="prev-trig" name="${obj.id}" lay-verify="${obj.config.required ? 'otherReq' : ''}">`;
					res += `<option value=""></option>`;
					//循环添加选项
					for (let i = 0; i < obj.config.options.length; i++) {
						res += `
						<option value="${obj.config.options[i].value}">${obj.config.options[i].text}</option>
						`;
					}
					res += `</select>`;
					res += `</div></div>`
					res += `</div>`;
					return res;
				},
				renderOption: function(obj,i) {
					var res = `
						<div class="layui-form-item opt-div act">
							<label class="layui-form-label handle" ><i class="layui-icon layui-icon-more-vertical drag-icon" style="display:none"></i></label>
							<div class="layui-input-inline" style="width: 20px;">
								<i class="layui-icon layui-icon-triangle-d" style="font-size: 16px;"></i>
							</div>
							<div class="layui-input-inline" style="width: 290px;">
								<input name="${obj.id}@${generateRandomId()}" value="${obj.config.options[i].text}" class="layui-input opt act" type="text" >
							</div>
							<div class="layui-input-inline inline-opt" style="width: 80px;height:38px;display:none;">
								<i class="layui-icon layui-icon-add-circle add-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 4px;float:left"></i>
								<i class="layui-icon layui-icon-reduce-circle del-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 0px;float:left;"></i>
							</div>
						</div>`;
					return res;
				}
			},
			input: {
				renderContent: function (obj) {
					var res = `
						<div class="layui-form-item">
							<label class="layui-form-label" ></label>
							<div class="layui-input-block" style="width: 400px">
							<div class="layui-input-wrap">
								<div class="layui-input-prefix">
								<i class="input-icon layui-icon ${obj.id}"></i>
								</div>
								<input type="text" data-id="${obj.id}" placeholder="请输入${quesElement.verify[obj.config.verify]||'文本'}" class="layui-input" readonly>
							</div>
							</div>
						</div>`;
					return res;
				},
				renderProperty: function (obj) {
					var res = `
						<div class="layui-form-item" >
							<label class="layui-form-label">校验类型</label>
							<div class="layui-input-block">
							<select name="interest" lay-filter="verify">
								<option value=""></option>`;
					for (const key in quesElement.verify) {
						res += `<option value="${key}" ${obj.config.verify == key ? 'selected' : ''}>${quesElement.verify[key]}</option>`;
					}
					res += `
							</select>
							</div>
						</div>`;
					return res;
				},
				renderPreview: function(obj) {
					var res = `
						<div class="layui-form-item">
							<label class="layui-form-label" ></label>
							<div class="layui-input-block" style="width: 400px">
								<div class="layui-input-wrap">
								<div class="layui-input-prefix">
								<i class="input-icon layui-icon ${obj.id} ${quesElement.iconClass[obj.config.verify]}"></i>
								</div>
								<input lay-filter="prev-trig" type="text" name="${obj.id}" placeholder="请输入${quesElement.verify[obj.config.verify]||'文本'}" class="layui-input prev-input" lay-verify="${obj.config.required ? 'otherReq' : ''}|${obj.config.verify}">
								</div>
							</div>
						</div>`;
					return res;
				}
			},
			textarea: {
				renderContent: function () {
					var res = `
						<div class="layui-form-item">
							<label class="layui-form-label" ></label>
							<div class="layui-input-block" style="width: 400px">
								<textarea name="" placeholder="多行文本框" class="layui-textarea" readonly></textarea>
							</div>
						</div>
					`;
					return res;
				},
				renderProperty: function () {
					var res = `
						<div class="layui-form-item" >
							<label class="layui-form-label">专属属性</label>
							<div class="layui-input-block">
							<input type="text" name="id" class="layui-input" value="checkbox" readonly>
							</div>
						</div>`;
					return res;
				},
				renderPreview: function(obj) {
					var res = `
						<div class="layui-form-item">
							<label class="layui-form-label" ></label>
							<div class="layui-input-block" style="width: 400px">
								<textarea lay-filter="prev-trig" name="${obj.id}" placeholder="多行文本框" class="layui-textarea" lay-verify="${obj.config.required ? 'otherReq' : ''}"></textarea>
							</div>
						</div>
					`;
					return res;
				}
			},
			mulinput: {
				renderContent: function (obj) {
					var res = `<div class="xxx ${obj.id} act">`;
					//循环添加选项
					for (let i = 0; i < obj.config.options.length; i++) {
						res += this.renderOption(obj,i);
					}
					res += `</div>`;
					return res;
				},
				renderProperty: function () {
					var res = `
						<div class="layui-form-item" >
							<label class="layui-form-label">专属属性</label>
							<div class="layui-input-block">
							<input type="text" name="id" class="layui-input" value="checkbox" readonly>
							</div>
						</div>`;
					return res;
				},
				renderPreview: function(obj) {
					var res = `<div >`;
					//循环添加选项
					for (let i = 0; i < obj.config.options.length; i++) {
						res += `
						<div class="layui-form-item opt-div act">
							<div class="layui-form-item">
								<label class="layui-form-label " ></label>
								<div class="layui-input-inline" style="width: 480px;margin-top:10px;">
									${obj.config.options[i].text}
								</div>
							</div>
							<div class="layui-form-item">
								<div class="layui-input-block" style="width: 290px;">
									<input name="${obj.id}@${i}" placeholder="填空区" class="layui-input" type="text" lay-verify="${obj.config.required ? 'otherReq' : ''}">
								</div>
							</div>
						</div>
						`;
					}
					res += `</div>`;
					return res;
				},
				renderOption: function(obj,i) {
					var res = `
						<div class="layui-form-item opt-div act">
							<div class="layui-form-item">
								<label class="layui-form-label handle" ><i class="layui-icon layui-icon-more-vertical drag-icon" style="display:none"></i></label>
								<div class="layui-input-inline opt act" style="width: 290px;">
									<input name="${obj.id}@${generateRandomId()}" value="${obj.config.options[i].text}" class="layui-input opt act" type="text" >
								</div>
								<div class="layui-input-inline inline-opt" style="width: 80px;height:38px;display:none;">
									<i class="layui-icon layui-icon-add-circle add-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 4px;float:left"></i>
									<i class="layui-icon layui-icon-reduce-circle del-opt act" data-id="${obj.id}" style="font-size: 20px;margin: 10px 0px;float:left;"></i>
								</div>
							</div>
							<div class="layui-form-item">
								<div class="layui-input-block" style="width: 290px;height: 60px">
									<input placeholder="填空区" class="layui-input" type="text" readonly>
								</div>
							</div>
						</div>
						`;
					return res;
				}
			},
			rate: {
				renderContent: function(obj) {
					var res = `
						<div class="layui-form-item">
							<label class="layui-form-label" ></label>
							<div class="layui-input-block" style="width: 400px">
								<div id="${obj.id}"></div>
							</div>
						</div>
					`;
					return res;
				},
				renderProperty: function () {
					var res = `
						<div class="layui-form-item" >
							<label class="layui-form-label">专属属性</label>
							<div class="layui-input-block">
							<input type="text" name="id" class="layui-input" value="checkbox" readonly>
							</div>
						</div>`;
					return res;
				},
				renderPreview: function(obj) {
					var res = `
						<div class="layui-form-item">
							<label class="layui-form-label" ></label>
							<div class="layui-input-block" style="width: 400px">
								<div name="${obj.id}" id="${obj.id}-pre"></div>
							</div>
						</div>
					`;
					return res;
				}
			},
			date: {
				renderContent: function(obj) {
					var res = `
						<div class="layui-form-item">
							<label class="layui-form-label" ></label>
							<div class="layui-input-inline layui-input-wrap">
								<div class="layui-input-prefix">
								<i class="layui-icon layui-icon-date"></i>
								</div>
								<input type="text" name="date" id="${obj.id}" lay-verify="date" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input" >
							</div>
						</div>
					`;
					return res;
				},
				renderProperty: function () {
					var res = `
						<div class="layui-form-item" >
							<label class="layui-form-label">专属属性</label>
							<div class="layui-input-block">
							<input type="text" name="id" class="layui-input" value="checkbox" readonly>
							</div>
						</div>`;
					return res;
				},
				renderPreview: function(obj) {
					var res = `
						<div class="layui-form-item">
							<label class="layui-form-label" ></label>
							<div class="layui-input-inline layui-input-wrap">
								<div class="layui-input-prefix">
								<i class="layui-icon layui-icon-date"></i>
								</div>
								<input type="text" name="date" id="${obj.id}-pre" lay-verify="date${obj.config.required ? '|otherReq' : ''}" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
							</div>
						</div>
					`;
					return res;
				}
			}
		};

		//存储题目信息
		var QuesBlock = function (options) {
			this.id = options.id,
			this.index = options.index,
			this.title = options.title,
			this.type = options.type,
			this.config = {}
		};

		//基础组件
		$('.menu1').click(function(e) {
			var _type = e.target.classList[2];
			var block = JSON.parse(JSON.stringify(quesElement[_type]));
			block.index = that.cur_no+1;
			block.id = _type + '_' + (that.cnt_id+1);
			that.addItem(block);
		});
		//题库
		$('.menu2').click(function(e) {
			var _id = e.target.classList[2];
			var block = JSON.parse(JSON.stringify(that.id_block[_id]));
			block.index = that.cur_no+1;
			block.id = block.type + '_' + (that.cnt_id+1);
			that.addItem(block);
		});

		//根据id获取题目信息
		function findBlockById(id) {
			var _block;
			for (let i = 0; i < that.dataList.length; i++) {
				if (that.dataList[i].id === id) {
					_block = that.dataList[i];
				}
			}
			return _block;
		};
		
		//生成组件
		ques.prototype.addItem = function(block,op,item) {
			that.cnt_id++;
			that.cnt_no++;
			$('.selected').removeClass('selected');
			that.cur_id = block.id;

			//that.dataList.push(block);
			that.dataList.splice(block.index-1,0,block);

			// that.id_index[block.id] = block.index;
			var _html = quesRender.midContentRender(block);
			
			var _ov = `<li class="right-list" data-id="${block.id}"><span class="list-index">${block.index}. </span><span data-id="${block.id}">${block.title ? block.title : '无标题'}</span></li>`;
			if(op === 'insert') {
				if(that.cur_no === 0)
					$("#overview").append(_ov);
				else if(block.index == 1)
					$("#overview").children().eq(0).before(_ov);
				else
					$("#overview").children().eq(block.index-2).after(_ov);
				item.outerHTML = _html;
			}
			else {
				if(that.cur_no === 0) {
					$("#overview").append(_ov);
					$("#mid-form-item").append(_html);
				}
				else {
					$("#overview").children().eq(that.cur_no==-1?that.cnt_no-1:that.cur_no-1).after(_ov);
					$("#mid-form-item").children().eq(that.cur_no==-1?that.cnt_no-1:that.cur_no-1).after(_html);
				}
			}
			
			form.render();

			// 删除
			$('.delete-item.act').on('click', function (e) {
				deleteItem(e.currentTarget.dataset.id);
			});
			//复制
			$('.copy-item.act').on('click', function (e) {
				copyItem(e.currentTarget.dataset.id);
			});
			//修改
			$('.title.act').change(function (e) {
				$(`span[data-id="${e.target.name}"]`).text(e.target.value);
				var _block = findBlockById(e.target.name);
				_block.title = e.target.value;
				$('#prop').html(quesRender.propertyRender(_block));
				$(`span[data-id="${e.target.name}"]`).click();//重新渲染设置
			});
			//点击
			$('.item.act').on('click', function (e) {
				var _block = findBlockById(e.currentTarget.dataset.id);
				that.cur_id = _block.id;
				that.cur_no = _block.index;
				$('#prop').html(quesRender.propertyRender(_block));
				form.render();
				$('.selected').removeClass('selected');
				$(`div[data-id="${_block.id}"]`).addClass('selected');

				document.querySelector('#mid-scroll').scrollTo({
					top:document.querySelector(`div[data-id="${_block.id}"]`).offsetTop-200,
					behavior: "smooth"
				});
			});
			$('.right-list').on('click', function(e) {
				document.querySelector('#mid-scroll').scrollTo({
					top:document.querySelector(`div[data-id="${e.currentTarget.dataset.id}"]`).offsetTop-200,
					behavior: "smooth"
				});
				$(`div[data-id="${e.currentTarget.dataset.id}"]`).click();
			});

			if (block.type === 'radio'|| block.type === 'checkbox' || block.type === 'select' || block.type === 'mulinput') {
				//添加选项
				Array.from(document.getElementsByClassName('xxx')).forEach(function(item, index) {
					var sortable = new Sortable(item, {
						animation: 150,
						ghostClass: 'blue-background-class',
						handle: '.handle',
						onUpdate: function (evt) {
							var _id = evt.target.classList[1];
							var _block = findBlockById(_id);
							var new_i = evt.newIndex;
							var old_i = evt.oldIndex;
							if(new_i > old_i) {
								var tmp = _block.config.options[old_i];
								for (let i = old_i; i < new_i; i++) {
									_block.config.options[i] = _block.config.options[i+1];
								}
								_block.config.options[new_i] = tmp;
							}
							else if(new_i < old_i) {
								var tmp = _block.config.options[old_i];
								for (let i = old_i; i > new_i; i--) {
									_block.config.options[i] = _block.config.options[i-1];
								}
								_block.config.options[new_i] = tmp;
							}
						},
					})
				});
				var _init_opt = function() {
					$('.opt.act').change(function(e) {
						var _arr = e.target.name.split('@');
						var _id = _arr[0];
						var _index;
						var _block = findBlockById(_id);
						if(_block.type === 'select' || _block.type === 'radio' || _block.type === 'checkbox') {
							// _index = Array.prototype.indexOf.call(e.target.parentNode.parentNode.parentNode.children, e.target.parentNode.parentNode);
							_index = getIndexOfElement(e.target.parentNode.parentNode);
						}
						else if(_block.type === 'mulinput') {
							// _index = Array.prototype.indexOf.call(e.target.parentNode.parentNode.parentNode.parentNode.children, e.target.parentNode.parentNode.parentNode);
							_index = getIndexOfElement(e.target.parentNode.parentNode.parentNode);
						}
						_block.config.options[_index].text = e.target.value;
						_block.config.options[_index].value = e.target.value;
					});
					$('.opt.act').on('click', function(e) {
						e.target.select();
					});
					$('.opt-div.act').on('mouseover', function(e) {
						e.currentTarget.querySelector(`.inline-opt`).style.display = 'block';
						e.currentTarget.querySelector(`.drag-icon`).style.display = 'block';
					});
					$('.opt-div.act').on('mouseout', function(e) {
						e.currentTarget.querySelector(`.inline-opt`).style.display = 'none';
						e.currentTarget.querySelector(`.drag-icon`).style.display = 'none';
					});
				};
				_init_opt();
				//删除选项
				var _del_opt = function(e) {
					var _block = findBlockById(e.currentTarget.dataset.id);
					// var _index = Array.prototype.indexOf.call(e.target.parentNode.parentNode.parentNode.children, e.target.parentNode.parentNode);
					var _index = getIndexOfElement(e.target.parentNode.parentNode);
					if(_block.config.options.length === 1) {
						layer.msg("至少保留一个选项！");
						return;
					}
					_block.config.options.splice(_index,1);
					if(_block.type === 'mulinput')
						e.target.parentNode.parentNode.parentNode.remove();
					else
						e.target.parentNode.parentNode.remove();
				};
				//添加选项
				var _add_opt = function (e) {
					var _block = findBlockById(e.currentTarget.dataset.id);
					var _id = e.currentTarget.dataset.id;
					var _index;
					var _opt;
					if(_block.type === 'select' || _block.type === 'radio' || _block.type === 'checkbox') {
						_opt = {text:'选项', value:'value', checked:false};
						// _index = Array.prototype.indexOf.call(e.target.parentNode.parentNode.parentNode.children, e.target.parentNode.parentNode);
						_index = getIndexOfElement(e.target.parentNode.parentNode);
					}
					else if(_block.type === 'mulinput') {
						_opt = {text:'填空项', value:'填空区'};
						// _index = Array.prototype.indexOf.call(e.target.parentNode.parentNode.parentNode.parentNode.children, e.target.parentNode.parentNode.parentNode);
						_index = getIndexOfElement(e.target.parentNode.parentNode.parentNode);
					}
					_block.config.options.splice(_index+1,0,_opt);
					$(`.xxx.${_id}`).children().eq(_index).after(quesRender[_block.type].renderOption(_block,_index+1));

					form.render();
					_init_opt();
					$('.del-opt.act').on('click', _del_opt);
					$('.add-opt.act').on('click', _add_opt);
					$('.act').removeClass('act');

				};
				//添加选项
				$('.add-opt.act').on('click', _add_opt);
				//删除选项
				$('.del-opt.act').on('click', _del_opt);
				//添加其他项
				$('.add-other.act').on('click', function(e) {
					var _block = findBlockById(e.currentTarget.dataset.id);
					var _id = e.currentTarget.dataset.id;
					var _opt = {text:'其他', value:'其他', checked:false, other: true, next:_block.index+2};
					_block.config.options.push(_opt);
					$(`.xxx.${_id}`).append(quesRender[_block.type].renderOption(_block,_block.config.options.length-1));

					form.render();
					_init_opt();
					$('.del-opt.act').on('click', _del_opt);
					$('.add-opt.act').on('click', _add_opt);
					$('.act').removeClass('act');
				});
				//批量导入选项
				$('.import-opt.act').on('click', function(e) {
					var _html = `
					<form class="layui-form" action="">
						<div class="layui-form-item layui-form-text">
							<label class="layui-form-label">导入选项</label>
							<div class="layui-input-block">
							<textarea name="options" placeholder="请输入内容" class="layui-textarea"></textarea>
							</div>
						</div>
						<button type="button" class="layui-btn" style="width: 100px;margin: 0px 50px;"
                                    lay-submit lay-filter="import-opt">导入</button>
					</form>
					`;
					layer.open({
						title: '批量导入选项',
						type: 1,
						area: ['50%', '50%'], // 宽高
						content: _html,
						success: function(){
							form.render();
							form.on('submit(import-opt)', function (data) {
								var opts = data.field.options.trim().split("\n");
								if(opts.length == 1 && opts[0] == '') {
									layer.msg("请填写选项!");
									return;
								}
								for (let i = 0; i < opts.length; i++) {
									var _index;
									var _opt;
									if(block.type === 'select' || block.type === 'radio' || block.type === 'checkbox') {
										_opt = {text:opts[i], value:'value', checked:false};
										// _index = Array.prototype.indexOf.call(e.target.parentNode.parentNode.parentNode.children, e.target.parentNode.parentNode);
										_index = getIndexOfElement(e.target.parentNode.parentNode);
									}
									else if(block.type === 'mulinput') {
										_opt = {text:opts[i], value:'填空区'};
										// _index = Array.prototype.indexOf.call(e.target.parentNode.parentNode.parentNode.parentNode.children, e.target.parentNode.parentNode.parentNode);
										_index = getIndexOfElement(e.target.parentNode.parentNode.parentNode);
									}
									block.config.options.push(_opt);
									$(`.xxx.${block.id}`).append(quesRender[block.type].renderOption(block,block.config.options.length-1));

									form.render();
									_init_opt();
									$('.del-opt.act').on('click', _del_opt);
									$('.add-opt.act').on('click', _add_opt);
									$('.act').removeClass('act');
								}
								layer.msg("保存成功!");
							});
						}
					});
				});
			}

			if(block.type === 'rate') {
				layui.rate.render({
					elem: `#${block.id}`,
					length: block.config.length,
					value: block.config.value,
					half: block.config.half,
					text: block.config.text,
					setText: function(value){ // 自定义文本的初始回调
						this.span.text(block.config.arr[value] || ( value + "星"));
					}
				});
			}
			if(block.type === 'date') {
				layui.laydate.render({
					elem: `#${block.id}`
				  });
			}

			$('.item.act').click();//点击新增的组件
			$('.act').removeClass('act');

			if(that.cnt_no > 1 && that.cur_no !== that.cnt_no) {
				that.reIndex(block.id);
			}
			
		};
		//删除组件
		function deleteItem(id) {
			for (let i = 0; i < that.dataList.length; i++) {
				if(that.dataList[i].id == id) {
					if(that.dataList[i].config.logic > 0) {
						layer.msg("该题目已参与" + that.dataList[i].config.logic + "个逻辑条件/事件，无法删除！");
						return;
					}
					that.dataList.splice(i,1);
					break;
				}
			}
			that.cnt_no--;
			$(`div[data-id="${id}"]`).remove();
			$(`li[data-id="${id}"]`).remove();
			
			that.reIndex();
			
			// delete that.id_index[id];
			if (that.cur_id === id) {
				that.cur_no = 0;
				$('#prop').html('');
			}
		};
		//复制组件
		function copyItem(id) {
			var block;
			for (let i = 0; i < that.dataList.length; i++) {
				if (that.dataList[i].id === id) {
					block = JSON.parse(JSON.stringify(that.dataList[i]));
					break;
				}
			}
			block.index = that.cur_no+1;
			block.id = block.type + '_' + (that.cnt_id+1);
			that.addItem(block);
		};
		//插入组件
		ques.prototype.insertItem = function(index, flag, type, item) {
			var that = this;
			var block;
			if(flag === 'm1')//基础组件
				block = JSON.parse(JSON.stringify(quesElement[type]));
			else if(flag === 'm2')//题库
				block = JSON.parse(JSON.stringify(that.id_block[type]));
			block.index = index;
			block.id = block.type + '_' + (that.cnt_id+1);
			that.addItem(block, 'insert', item);
		};

		//生成预览页面
		ques.prototype.getPreview = function() {
			var title = $('#title').val();
			var res = `<h2 style="text-align: center;">${title}</h2>`;
			res += '<form class="layui-form" action="" >';

			for (let i = 0; i < this.dataList.length; i++) {
				res += quesRender.previewRender(this.dataList[i]);
			}
			res += `<div class="layui-form-item">
						<div class="layui-input-block" style="margin:auto 0px;text-align: center;">
						<button type="button" class="layui-btn" lay-submit lay-filter="pre-submit">提交</button>
						</div>
					</div>`;
			res += '</form>';
			return res;
		};
		//渲染非表单组件
		ques.prototype.renderOtherItem = function() {
			for (let i = 0; i < that.dataList.length; i++) {
				if(that.dataList[i].type === 'rate') {
					var obj = that.dataList[i];
					layui.rate.render({
						elem: `#${obj.id}-pre`,
						length: obj.config.length,
						value: obj.config.value,
						half: obj.config.half,
						text: obj.config.text,
						setText: function(value){ // 自定义文本的初始回调
							this.span.text(obj.config.arr[value] || ( value + "星"));
						}
					});
				}
				if(that.dataList[i].type === 'date') {
					var obj = that.dataList[i];
					layui.laydate.render({
						elem: `#${obj.id}-pre`
					});
				}
			}
			$('.other-input.act').change(function(e) {
				// var _index = Array.prototype.indexOf.call(e.target.parentNode.parentNode.parentNode.children, e.target.parentNode.parentNode);
				var _index = getIndexOfElement(e.target.parentNode.parentNode);
				e.target.parentNode.firstElementChild.value = e.target.value;
				var _block = findBlockById(e.target.dataset.id);
				_block.config.options[_index].value = e.target.value;
			});
			$('.act').removeClass('act');
		};

		ques.prototype.setRequired = function(id, required) {
			var _block = findBlockById(id);
			_block.config.required = required;
			if(required) {
				$(`label[name=${id}]`).addClass('required');
			}
			else {
				$(`label[name=${id}]`).removeClass('required');
			}
		};
		ques.prototype.setVerify = function(id, verify) {
			var _block = findBlockById(id);
			_block.config.verify = verify;
			$(`.input-icon.${_block.id}`).removeClass().addClass(`input-icon layui-icon ${quesElement.iconClass[verify]} ${_block.id}`);
			$(`input[data-id="${_block.id}"]`).attr("placeholder", `请输入${quesElement.verify[_block.config.verify]||'文本'}`);
		};

		ques.prototype.batchDel = function(idList) {
			for (let i = 0; i < idList.length; i++) {
				for (let j = 0; j < that.dataList.length; j++) {
					if(that.dataList[j].id == idList[i]) {
						if(that.dataList[j].config.logic > 0) {
							layer.msg(`题目${j+1}已参与${that.dataList[j].config.logic}个逻辑条件/事件，无法删除！`);
							that.reIndex();
							return;
						}
						that.dataList.splice(j,1);
						break;
					}
				}
				that.cnt_no--;
				$(`div[data-id="${idList[i]}"]`).remove();
				$(`li[data-id="${idList[i]}"]`).remove();
				
				// delete that.id_index[idList[i]];
				if (that.cur_id === idList[i]) {
					that.cur_no = 0;
					$('#prop').html('');
				}
			}
			that.reIndex();
			layer.msg("批量删除成功");
		};

		ques.prototype.hideItems = function(id, index) {
			console.log("ok",index);
			var _block = findBlockById(id);
			var _next = _block.config.options[index].next;
			console.log(_block,_next);
			for (let i = _block.index; i < _next-1; i++) {
				console.log(that.dataList[i].id);
				console.log($(`div[data-id="${that.dataList[i].id}"]`));
				$(`div[data-id="${that.dataList[i].id}"]`)[1].style.display = 'none';
			}
		};

		function addCondition(idx) { //idx = logic_item的编号
			if(!that.conds_count[idx])
				that.conds_count[idx] = 0;
			that.conds_count[idx] += 1;
			var count = that.conds_count[idx];
			
			var res =	`<div class="layui-form-item">`;
							if(count == 1) {
								res += `<button type="button" class="layui-btn layui-btn-sm del-logic act" style="float: right;">删除</button>
								
								<label class="layui-form-label">如果</label>`;
							}
							else if(count == 2) {
								res += `<label class="layui-form-label" style="width:10px;"></label>
										<div class="layui-input-inline" style="width:60px;">
										<select lay-filter="relation" name="l${idx}_relation">
											<option value="or">或</option>
											<option value="and">且</option>
										</select>
										</div>`;
							}
							else {
								res += `<label class="layui-form-label"></label>`;
							}
			res +=			`<div class="layui-input-inline">
							<select lay-filter="cas-1" name="l${idx}_c${count}a">
								<option value="">请选择</option>`;
			for (let k = 0; k < that.dataList.length; k++) {
				var e = that.dataList[k];
				res += `<option value="${e.id}">${e.title || e.id}</option>`;
			}
			res += `
							</select>
							</div>
							<div class="layui-input-inline">
							<select lay-filter="cas-2" name="l${idx}_c${count}b">
								<option value="">请选择</option>
							</select>
							</div>
							<div class="layui-input-inline">
							<select lay-filter="cas-3" name="l${idx}_c${count}c">
								<option value="">请选择</option>
							</select>
							</div>`;
			if(count == 1) {
				res += `<div class="layui-input-inline" style="width: 70px;height:38px;">
							<i class="layui-icon layui-icon-add-circle add-condition act" style="font-size: 20px;margin: 10px 4px;float:left"></i>
							<i class="layui-icon layui-icon-reduce-circle del-condition act" style="font-size: 20px;margin: 10px 0px;float:left;"></i>
						</div>`
			}				
			res += `</div>`;
			return res;
		};
		function addEvent(idx) {
			if(!that.events_count[idx])
				that.events_count[idx] = 0;
			that.events_count[idx] += 1;
			var count = that.events_count[idx];

			var res = `
					<div class="layui-form-item">
						<label class="layui-form-label">${count == 1?'则':''}</label>
						<div class="layui-input-inline">
						<select name="l${idx}_e${count}a">
							<option value="">请选择</option>
							<option value="show">显示</option>
							<option value="hide">隐藏</option>
							<option value="goto">跳至</option>
						</select>
						</div>
						<div class="layui-input-inline">
						<select name="l${idx}_e${count}b">
							<option value="">请选择</option>`;
			for (let k = 0; k < that.dataList.length; k++) {
				var e = that.dataList[k];
				res += `<option value="${e.id}">${e.title || e.id}</option>`;
			}
			res +=		`</select>
						</div>`;
			if(count == 1) {
				res += `<div class="layui-input-inline" style="width: 70px;height:38px;">
							<i class="layui-icon layui-icon-add-circle add-event act" style="font-size: 20px;margin: 10px 4px;float:left"></i>
							<i class="layui-icon layui-icon-reduce-circle del-event act" style="font-size: 20px;margin: 10px 0px;float:left;"></i>
						</div>`;
			}
			res +=	`</div>`;
			return res;
		};
		function addLogicItem(i, data, is_new) {
			if(is_new) {
				that.logic_count += 1;
				var res = `
						<div name="${that.logic_count}" class="layui-form-item" style="background-color:aliceblue;padding:4px;margin:10px 10px;">
						<div class="conditions">`;
						res += addCondition(that.logic_count);
				res +=	`</div>`;
				res +=	`<div class="events">`;
						res += addEvent(that.logic_count);
				res +=	`</div>`;
				res += 	`</div>`;
				return res;
			}
			if(!data) return;
			i += 1;
			that.logic_count += 1;
			var res = `
					<div name="${that.logic_count}" class="layui-form-item" style="background-color:aliceblue;padding:4px;margin:10px 10px;">
						<div class="conditions">`;
			for (let j = 1; j <= data.conditions.length; j++) {
				if(!that.conds_count[i])
					that.conds_count[i] = 0;
				that.conds_count[i] += 1;

				var cond = data.conditions[j-1];
				res +=	`<div class="layui-form-item">`;
							if(j == 1) {
								res += `<button type="button" class="layui-btn layui-btn-sm del-logic act" style="float: right;">删除逻辑</button>
								<label class="layui-form-label">如果</label>`;
							}
							else if(j == 2) {
								res += `<label class="layui-form-label" style="width:10px;"></label>
										<div class="layui-input-inline" style="width:60px;">
										<select name="l${i}_relation">
											<option value="or" ${data.relation === 'or'?'selected':''}>或</option>
											<option value="and" ${data.relation === 'and'?'selected':''}>且</option>
										</select>
										</div>`;
							}
							else {
								res += `<label class="layui-form-label"></label>`;
							}
				res +=		`<div class="layui-input-inline">
							<select lay-filter="cas-1" name="l${i}_c${j}a">
								<option value="">请选择</option>`;
				for (let k = 0; k < that.dataList.length; k++) {
					var e = that.dataList[k];
					res += `<option value="${e.id}" ${e.id === cond.block_id?'selected':''}>${e.title || e.id}</option>`;
				}
				res += `
							</select>
							</div>
							<div class="layui-input-inline">
							<select lay-filter="cas-2" name="l${i}_c${j}b">
								<option value="">请选择</option>`;
				var _type = cond.block_id.split('_')[0];
				if(_type == 'radio' || _type == 'checkbox' || _type == 'select'){
				res +=			`<option value="eq" ${cond.op === 'eq'?'selected':''}>选中</option>
								<option value="ne" ${cond.op === 'ne'?'selected':''}>未选中</option>
								<option value="show" ${cond.op === 'show'?'selected':''}>显示</option>
								<option value="hide" ${cond.op === 'hide'?'selected':''}>未显示</option>`;
				}
				else {
				res +=			`<option value="is" ${cond.op === 'is'?'selected':''}>等于</option>
								<option value="show" ${cond.op === 'show'?'selected':''}>显示</option>
								<option value="hide" ${cond.op === 'hide'?'selected':''}>未显示</option>`;
				}
				res +=		`</select>
							</div>
							<div class="layui-input-inline">`;
				if(cond.op === 'is') {
					res += `<input type="text" placeholder="请输入" class="layui-input" name="l${i}_c${j}c" value="${cond.value}"></input>`;
				}
				else if(cond.op === 'show' || cond.op === 'hide'){
					res += `<select lay-filter="cas-3" name="l${i}_c${j}c" disabled><option value="">请选择</option></select>`;
				}
				else if(cond.op === 'eq' || cond.op === 'ne'){
					res += `<select lay-filter="cas-3" name="l${i}_c${j}c"><option value="">请选择</option>`;
					var _block = findBlockById(cond.block_id);
					for (let k = 0; k < _block.config.options.length; k++) {
						var _opt = _block.config.options[k];
						res += `<option value="${_opt.value}" ${_opt.value === cond.value?'selected':''}>${_opt.text}</option>`;
					}
					res += `</select>`;
				}
				res +=		`</div>`;
				if(j == 1) {
					res += `<div class="layui-input-inline" style="width: 70px;height:38px;">
								<i class="layui-icon layui-icon-add-circle add-condition act" style="font-size: 20px;margin: 10px 4px;float:left"></i>
								<i class="layui-icon layui-icon-reduce-circle del-condition act" style="font-size: 20px;margin: 10px 0px;float:left;"></i>
							</div>`;
				}
				res +=	`</div>`;
			}
				res +=	`</div>`;
				res +=	`<div class="events">`;
			for (let j = 1; j <= data.events.length; j++) {
				if(!that.events_count[i])
					that.events_count[i] = 0;
				that.events_count[i] += 1;
				var event = data.events[j-1];
				res += `
						<div class="layui-form-item">
							<label class="layui-form-label">则</label>
							<div class="layui-input-inline">
							<select name="l${i}_e${j}a">
								<option value="">请选择</option>
								<option value="show" ${event.action === 'show'?'selected':''}>显示</option>
								<option value="hide" ${event.action === 'hide'?'selected':''}>隐藏</option>
								<option value="goto" ${event.action === 'goto'?'selected':''}>跳至</option>
							</select>
							</div>
							<div class="layui-input-inline">
							<select name="l${i}_e${j}b">
							<option value="">请选择</option>`;
				for (let k = 0; k < that.dataList.length; k++) {
					var e = that.dataList[k];
					res += `<option value="${e.id}" ${e.id === event.block_id?'selected':''}>${e.title || e.id}</option>`;
				}
				res +=		`</select>
							</div>`;
				if(j == 1) {
				res +=		`<div class="layui-input-inline" style="width: 70px;height:38px;">
								<i class="layui-icon layui-icon-add-circle add-event act" style="font-size: 20px;margin: 10px 4px;float:left"></i>
								<i class="layui-icon layui-icon-reduce-circle del-event act" style="font-size: 20px;margin: 10px 0px;float:left;"></i>
							</div>`;
				}
				res +=	'</div>';
			}
				res +=	`</div>`;
				res += 	`</div>`;
			return res;
		};
		ques.prototype.getLogicView = function() {
			console.log(quesLogic.logicItemList);
			var res = '<form class="layui-form" action="">';
			res += `
					<div class="layui-form-item">
						<button type="button" class="layui-btn layui-btn-sm add-logic act" style="float: right;">添加逻辑</button>
					</div>`;
			res += '<div id="logic-form">';
			for (let i = 0; i < quesLogic.logicItemList.length; i++) {
				res += addLogicItem(i, quesLogic.logicItemList[i]);
			}
			res += '</div>';
			res += `<div class="layui-form-item">
						<div class="layui-input-block" style="margin:auto 0px;text-align: center;">
						<button type="button" class="layui-btn" lay-submit lay-filter="logic-save">保存</button>
						</div>
					</div>`;
			res += '</form>';
			return res;
		};

		//弹窗页面渲染
		ques.prototype.renderBatchDelView = function() {};
		ques.prototype.renderPreview = function() {};

		ques.prototype.renderLogicView = function() {
			var that = this;
			that.logic_count = 0;
			that.conds_count = {};
			that.events_count = {};
			var _html = that.getLogicView();
			
			layer.open({
				title: '题目逻辑',
				type: 1,
				area: ['65%', '90%'], // 宽高
				content: _html,
				success: function() {
					form.render();
					$('.add-logic.act').on('click', function() {
						$("#logic-form").append(addLogicItem(null,null,true));
						form.render();
						$('.del-logic.act').on('click', function(e) {
							e.target.parentNode.parentNode.parentNode.remove();
						});
						$('.copy-logic.act').on('click', function(e) {
							console.log(e);
						});
						$('.add-condition.act').on('click', function(e) {
							var i = e.target.parentNode.parentNode.parentNode.parentNode.getAttribute('name');
							e.target.parentNode.parentNode.parentNode.insertAdjacentHTML('beforeend',addCondition(i));
							form.render();
						});
						$('.del-condition.act').on('click', function(e) {
							deleteLine(e,0);
						});
						$('.add-event.act').on('click', function(e) {
							var i = e.target.parentNode.parentNode.parentNode.parentNode.getAttribute('name');
							e.target.parentNode.parentNode.insertAdjacentHTML('afterend',addEvent(i));
							form.render();
						});
						$('.del-event.act').on('click', function(e) {
							deleteLine(e,1);
						});
						$('.act').removeClass('act');

						initSelect();
					});
					$('.del-logic.act').on('click', function(e) {
						e.target.parentNode.parentNode.parentNode.remove();
					});
					$('.copy-logic.act').on('click', function(e) {
						console.log(e);
					});
					$('.add-condition.act').on('click', function(e) {
						var i = e.target.parentNode.parentNode.parentNode.parentNode.getAttribute('name');
						e.target.parentNode.parentNode.parentNode.insertAdjacentHTML('beforeend',addCondition(i));
						form.render();
					});
					$('.del-condition.act').on('click', function(e) {
						deleteLine(e,0);
					});
					$('.add-event.act').on('click', function(e) {
						var i = e.target.parentNode.parentNode.parentNode.parentNode.getAttribute('name');
						e.target.parentNode.parentNode.insertAdjacentHTML('afterend',addEvent(i));
						form.render();
					});
					$('.del-event.act').on('click', function(e) {
						deleteLine(e,1);
					});
					$('.act').removeClass('act');

					initSelect();
					form.on('submit(logic-save)', function(data) {
						layer.msg("保存成功！");
						console.log(data);
						var res = [];
						var conditions = [], relation = '', events = [];
						for (let i = 0; i < that.dataList.length; i++) {
							that.dataList[i].config.logic = 0;
						}

						var i = 1, pre_li = '', cond = {}, trig = {};
						for (const key in data.field) {
							var _arr = key.split('_');
							var s1 = _arr[0], s2 = _arr[1];

							if(s2 === 'relation') {
								relation = data.field[key];
								i = 0;
							}
							else if(s2[0] === 'c') {
								if(s1 !== pre_li && pre_li !== '') {
									// quesLogic.saveLogicItem(conditions, relation, events);
									res.push({'conditions':conditions, 'relation':relation, 'events':events});
									conditions = [], relation = '', events = [];
									pre_li = s1;
								}
								else if(pre_li === '') {
									pre_li = s1;
								}
								if(i%3 == 1) {
									cond['block_id'] = data.field[key];
									var _block = findBlockById(data.field[key]);
									_block.config.logic += 1;
								}else if(i%3 == 2){
									cond['op'] = data.field[key];
								}else {
									cond['value'] = data.field[key];
									cond['status'] = false;
									conditions.push(cond);
									cond = {};
									i = 0;
								}
							}
							else if(s2[0] === 'e') {
								if(i%2 == 1) {
									trig['action'] = data.field[key];
								}else {
									trig['block_id'] = data.field[key];
									var _block = findBlockById(data.field[key]);
									_block.config.logic += 1;
									events.push(trig);
									trig = {};
									i = 0;
								}
							}
							i += 1;
						}
						// quesLogic.saveLogicItem(conditions, relation, events);
						res.push({'conditions':conditions, 'relation':relation, 'events':events});
						quesLogic.saveLogicItems(res);
					});
				}
			});
			function deleteLine(e, op) {
				// var _index = Array.prototype.indexOf.call(e.target.parentNode.parentNode.parentNode.lastElementChild.children, e.target.parentNode.parentNode.parentNode.lastElementChild);
				var _index = getIndexOfElement(e.target.parentNode.parentNode.parentNode.lastElementChild);
				if(_index == 0) {
					layer.msg("至少保留一项！");
					return;
				}
				e.target.parentNode.parentNode.parentNode.lastElementChild.remove();
				var i = e.target.parentNode.parentNode.parentNode.parentNode.getAttribute('name');
				if(op === 0)
					that.conds_count[i] -= 1;
				else
					that.events_count[i] -= 1;
			};
			function initSelect() {
				form.on('select(cas-1)', function(data) {
					var _block = findBlockById(data.value);
					if(_block.type == 'radio' || _block.type == 'checkbox' || _block.type == 'select') {
						var e = document.querySelector(`select[name=${data.elem.name.slice(0,-1) + 'b'}]`);
						e.innerHTML = '<option value="">请选择</option>';
						e.options.add(new Option("选中",'eq'));
						e.options.add(new Option("未选中",'ne'));
						e.options.add(new Option("显示",'show'));
						e.options.add(new Option("未显示",'hide'));

						e = document.querySelector(`select[name=${data.elem.name.slice(0,-1) + 'c'}]`);
						if(e === null) {
							e = document.querySelector(`input[name=${data.elem.name.slice(0,-1) + 'c'}]`);
							e.outerHTML = `<select name="${data.elem.name.slice(0,-1) + 'c'}"></select>`;
						}
						e.innerHTML = '<option value="">请选择</option>';
						e.removeAttribute('disabled');
					}
					else {
						var e = document.querySelector(`select[name=${data.elem.name.slice(0,-1) + 'b'}]`);
						e.innerHTML = '<option value="">请选择</option>';
						if(_block.type == 'input' || _block.type == 'textarea')
							e.options.add(new Option("等于",'is'));
						e.options.add(new Option("显示",'show'));
						e.options.add(new Option("未显示",'hide'));

						e = document.querySelector(`select[name=${data.elem.name.slice(0,-1) + 'c'}]`);
						if(e === null) {
							e = document.querySelector(`input[name=${data.elem.name.slice(0,-1) + 'c'}]`);
							e.outerHTML = `<select name="${data.elem.name.slice(0,-1) + 'c'}"></select>`;
						}
						e.innerHTML = '<option value="">请选择</option>';
						e.setAttribute('disabled',true);
					}
					form.render('select');
				});
				form.on('select(cas-2)', function(data) {
					if(data.value == 'is') {
						var e = document.querySelector(`select[name=${data.elem.name.slice(0,-1) + 'c'}]`);
						e.nextElementSibling.innerHTML = '';
						e.outerHTML = `<input type="text" placeholder="请输入" class="layui-input" name="${data.elem.name.slice(0,-1) + 'c'}">`;
					}
					else if(data.value == 'show' || data.value == 'hide'){
						var e = document.querySelector(`input[name=${data.elem.name.slice(0,-1) + 'c'}]`);
						if(e === null) {
							e = document.querySelector(`select[name=${data.elem.name.slice(0,-1) + 'c'}]`);
						}
						e.outerHTML = `<select name="${data.elem.name.slice(0,-1) + 'c'}"><option value="">请选择</option></select>`;
						e = document.querySelector(`select[name=${data.elem.name.slice(0,-1) + 'c'}]`);
						e.setAttribute('disabled',true);
					}
					else if(data.value == 'eq' || data.value == 'ne') {
						var e = document.querySelector(`select[name=${data.elem.name.slice(0,-1) + 'c'}]`);
						e.innerHTML = '<option value="">请选择</option>';
						var _id = document.querySelector(`select[name=${data.elem.name.slice(0,-1) + 'a'}]`).value;
						var _block = findBlockById(_id);
						for (let i = 0; i < _block.config.options.length; i++) {
							e.options.add(new Option(_block.config.options[i].text,_block.config.options[i].value));
						}
						e.removeAttribute('disabled');
					}
					form.render('select');

				});
				form.on('select(relation)', function(data) {
					if(data.value === 'and') {
						var i = 1;
						while(1) {
							var s = data.elem.name.split('_')[0] + '_e' + String(i) + 'a';
							var e = document.querySelector(`select[name=${s}]`);
							if(e === null) break;
							if(e.value === 'goto') {
								e.value = "";
							}
							e.options[3].disabled = true;
							i += 1;
						}
					}
					else {
						var i = 1;
						while(1) {
							var s = data.elem.name.split('_')[0] + '_e' + String(i) + 'a';
							var e = document.querySelector(`select[name=${s}]`);
							if(e === null) break;
							e.options[3].disabled = false;
							i += 1;
						}
					}
					form.render('select');
				});
			};
		};

		ques.prototype.executeLogic = function(id, value) {
			var _block = findBlockById(id);
			quesLogic.handleLogic(_block.index, id, value);
			var i = 1;
			Array.from(document.getElementsByClassName('prev-index')).forEach(function (item, index) {
				if(item.parentNode.parentNode.style.display === 'block') {
					item.innerHTML = String(i) + ".";
					i += 1;
				}
			});
		};
	};

	exports(MOD_NAME, new ques());
});
